package org.reserved.util;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.reserved.loadbalance.PropertyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * 钉钉通知
 **/
@Component
public class DingTalkUtil {

    private static final String MSG_TYPE_TEXT = "text";

    private static final String MSG_CHARSET = "UTF-8";

    private static final String MSG_ALGORITHM = "HmacSHA256";

    private static final String ACCESS_TOKEN_PREFIX = "https://oapi.dingtalk.com/robot/send?access_token=";

    @Value("${spring.application.name}")
    private String projectName;

    private DingTalkClient client;

    private List<String> mobileList = null;

    private boolean isAtAll = true;

    @Autowired
    public DingTalkUtil(PropertyUtil propertiesPojo) {
        if (StringUtils.isEmpty(propertiesPojo.getDingSecret()) || StringUtils.isEmpty(propertiesPojo.getDingAccessToken())) {
            return;
        }
        if (propertiesPojo.getMobileList() != null && propertiesPojo.getMobileList().size() > 0) {
            this.mobileList = propertiesPojo.getMobileList();
            this.isAtAll = false;
        }
        String accessToken = ACCESS_TOKEN_PREFIX + propertiesPojo.getDingAccessToken();
        try {
            client = new DefaultDingTalkClient(accessToken + sign(propertiesPojo.getDingSecret()));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向钉钉群内发送text消息
     *
     * @param content 消息内容
     */
    public OapiRobotSendResponse sendText(String content) {
        if (client == null) {
            return null;
        }

        if (StringUtils.isEmpty(content)) {
            return null;
        }

        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(content);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
        at.setIsAtAll(isAtAll);
        if (!CollectionUtils.isEmpty(mobileList)) {
            at.setAtMobiles(mobileList);
            request.setAt(at);
        }
        request.setMsgtype(DingTalkUtil.MSG_TYPE_TEXT);
        request.setText(text);

        OapiRobotSendResponse response = new OapiRobotSendResponse();
        try {
            response = client.execute(request);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return response;
    }

    private String sign(String secret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        long timestamp = System.currentTimeMillis();
        Mac mac = Mac.getInstance(MSG_ALGORITHM);
        mac.init(new SecretKeySpec(secret.getBytes(MSG_CHARSET), MSG_ALGORITHM));
        byte[] signByte = mac.doFinal((timestamp + "\n" + secret).getBytes(MSG_CHARSET));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signByte)), MSG_CHARSET);
        return "&timestamp=" + timestamp + "&sign=" + sign;
    }
}

